package com.b2b.controller;

import com.alibaba.fastjson.JSONObject;
import com.b2b.model.entity.SMS;
import com.b2b.util.SMSUtil;

import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/sms")
@PropertySource("classpath:config.properties")
public class SMSController {
    //点击发送验证码
    @GetMapping("/sendMs")
    public String sendMs (HttpServletRequest request, @RequestBody SMS sms){
        String phoneNumber = sms.getPhone();
        Integer min = 1;
        sms.setMin(min);
        if(phoneNumber!=null&&!phoneNumber.equals("")){
            return SMSUtil.sendSMS(request,sms);
        }else{
            return "error";
        }
    }
    //点击注册
    @GetMapping("/register")
    public Object register(HttpServletRequest request, SMS sms) {
        String code = sms.getCode();
        JSONObject json = (JSONObject)request.getSession().getAttribute("MsCode");
        if(!json.getString("Code").equals(code)){
            return "验证码错误";
        }
        //我这里模拟了一分钟
        if((System.currentTimeMillis() - json.getLong("createTime")) > 1000L * 60 * sms.getMin()){
            return "验证码过期";
        }
        //将用户信息存入数据库、这里省略
        return "success";
    }
}
